<template>
  <div>
    <!--引用表格-->
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" v-auth="'xl:xl_customer_shipment:exportXls'" preIcon="ant-design:export-outlined"
          @click="onExportXls"> 导出</a-button>


        <j-upload-button name="file" type="primary" preIcon="ant-design:import-outlined"
          @click="batchHandleBackPassDelivery2" v-auth="'lx:xl_customer_orde:batchBckPass'">批量回传快递单号</j-upload-button>

        <a-button type="default"
          @click="handleExportXls('批量回传快递单号', '/xl/template/downloadTemplateXls?template=deliveryCodeImport')"
          v-auth="'lx:xl_customer_orde:downBakctamp'">
          <Icon icon="line-md:download-off-loop" />下载回传模板
        </a-button>

        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="4" @click="batchHandleTakeDelivery" v-auth="'lx:xl_customer_orde:takeDelivery'"
                v-if="getProps('2')">
                <Icon icon="ant-design:edit-outlined"></Icon>
                收货
              </a-menu-item>
              <a-menu-item key="4" @click="batchHandleBackPassDelivery" v-auth="'lx:xl_customer_orde:batchBckPass'">
                <Icon icon="ant-design:edit-outlined"></Icon>
                回传物流信息
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
        <!-- 高级查询 -->
        <!-- <super-query :config="superQueryConfig" @search="handleSuperQuery" /> -->
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
      </template>
      <!--字段回显插槽-->
      <template v-slot:bodyCell="{ column, record, index, text }">
      </template>

      <template #logisticsInfo="{ text, record }">
        <template v-if="!!record.deliveryCode">
          <div>
            <div>物流类型：{{ record.deliveryWay_dictText }}</div>
            <div>快递公司：{{ record.deliveryType_dictText }}</div>
            <div>快递单：{{ record.deliveryCode }}
              <!-- <Icon icon="solar:copy-outline"  @click="copys(record)"/> -->
              <a href="javascript:void(0)" @click="copys(text)">
                <Icon icon="solar:copy-outline"></Icon>
              </a>
            </div>
          </div>
        </template>
      </template>

    </BasicTable>
    <!-- 表单区域 -->
    <AllModal @register="submitTakeDeliveryModal" :schemas="voucherFormSchema" :apiUrl="submitTakeDelivery"
      :height="320" @success="handleSuccess" />
    <AllModal @register="backPassDeliveryModal" :schemas="backPassFormSchema" :apiUrl="backPassDelivery" :height="200"
      @success="handleSuccess" />
    <AllTaskFlowDrawer @register="registerDrawer" />
    <XlCustomerShipmentModal @register="registerModal" @success="handleSuccess"></XlCustomerShipmentModal>
  </div>
</template>

<script lang="ts" name="xl-xlCustomerShipment" setup>
import { ref, reactive, computed, unref, onMounted } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { useModal } from '/@/components/Modal';
import XlCustomerShipmentModal from './components/XlCustomerShipmentModal.vue'
import { columns, searchFormSchema, superQuerySchema, pageType, voucherFormSchema, backPassFormSchema } from './XlCustomerShipment.data';
import { list, backPassDelivery, queryTrack, getExportUrl, takeDelivery, submitTakeDelivery, queryOrderByCode } from './XlCustomerShipment.api';
import { exportPdfStream } from '/@/views/xl/customer_orde/XlCustomerOrde.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import AllModal from '/@/views/xl/customer_orde/components/AllModal.vue';
import { useMessage } from "/@/hooks/web/useMessage";
import { useDrawer } from '/@/components/Drawer';
import AllTaskFlowDrawer from './components/AllTaskFlowDrawer.vue';
import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
import { useMethods } from '/@/hooks/system/useMethods';
const { handleExportXls, handleExportXlsx, handleImportXls } = useMethods();

const { createConfirm, createMessage } = useMessage();
const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();

const props = defineProps({
  pageType: { type: String, default: '0' },
});

// 自动请求并暴露内部方法
onMounted(() => {
  pageType.value = props.pageType;
});

//页面类型读取
const getProps = (val?) => {
  if (!!val) {
    return props.pageType === val;
  }
  return props.pageType === '0';
}


//注册model
const [submitTakeDeliveryModal, submitTakeDeliveryUseModal] = useModal();
const [backPassDeliveryModal, backPassDeliveryUseModal] = useModal();
const [registerModal, { openModal }] = useModal();
//流程橱柜
const [registerDrawer, { openDrawer }] = useDrawer();
//注册table数据
const { prefixCls, tableContext, onExportXls,onImportXls } = useListPage({
  tableProps: {
    title: '发货单',
    api: list,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [
      ],
      fieldMapToTime: [
      ],
    },
    actionColumn: {
      width: 250,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
    beforeFetch: (params) => {
      params.pageType = props.pageType; //带上页面类型参数
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "发货单",
    url: getExportUrl,
    params: queryParam,
  },
})

const [registerTable, { reload }, { rowSelection, selectedRowKeys, selectedRows }] = tableContext

// 高级查询配置
const superQueryConfig = reactive(superQuerySchema);

/**
 * 高级查询事件
 */
function handleSuperQuery(params) {
  Object.keys(params).map((k) => {
    queryParam[k] = params[k];
  });
  reload();
}

import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
function copys(text) {
  const { isSuccessRef } = useCopyToClipboard(text);
  //console.log(isSuccessRef);

}
/**
 * 详情
*/
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}

/**
 * 批量收货
 */
async function batchHandleTakeDelivery() {
  let isFLa = true
  selectedRows.value?.forEach(item => {
    if (item.state != "2") {
      isFLa = false
    }
  })
  if (isFLa) {
    createConfirm({
      iconType: 'warning',
      title: '确认批量收货',
      content: '是否批量收货选中数据',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        await takeDelivery({ id: selectedRowKeys.value?.join(',') });
        handleSuccess()
        return;
      }
    });
  } else {
    createMessage.warning('不是已发货和已收货的不能操作！')
  }
}

/**
 * 收货
 */
//  async function handleTakeDelivery(record) {
//   await takeDelivery({ id: record.id });
//   handleSuccess();
// }


// /**
//  * 收货凭证
//  */
//  async function handleSubmitTakeDelivery(record) {
//   submitTakeDeliveryUseModal.openModal(true, {
//     title: '收货凭证提交',
//     record: {id: record?.id},
//   });
// }

/**
 * 批量物流信息回传
 */
async function batchHandleBackPassDelivery(record) {
  let isFLa = true
  selectedRows.value?.forEach(item => {
    if (!!item.deliveryCode) {
      isFLa = false
    }
  })
  if (isFLa) {
    backPassDeliveryUseModal.openModal(true, {
      title: '批量物流信息回传',
      record: {id: selectedRowKeys.value?.join(',')}, //只传入批量id
    });
  } else {
    createMessage.warning('已回传的不能操作！')
  }
}

function batchHandleBackPassDelivery2(file) {
  handleImportXls(file, '/xl/xlCustomerShipment/importBatchExcel', '').then(() => {
    handleSuccess();
  });
}
/**
 * 回传快递单号
 */
async function handleBackPassDelivery(record) {
  backPassDeliveryUseModal.openModal(true, {
    title: '回传快递单号',
    record: record,
  });
}

//物料查询
function handleQueryTrack(record) {
  openDrawer(true, {
    apiUrl: queryTrack,
    params: {
      comp: record?.deliveryType,           //快递公司
      logisticorder: record?.deliveryCode,  //快递单号
      phone: '',
    },
  });
}

/**
 * PDF导出
 */
async function handleExcelConfigId(record) {
  var one = await queryOrderByCode({ orderCode: record?.orderCode })
  var info = await exportPdfStream({
    excelConfigId: "1011051575872913408",
    queryParam: {
      orderCode: record?.orderCode,
      receiptZone: getAreaTextByCode(one?.receiptZone),
      token: userStore.getToken,
      pageNo: "1",
      pageSize: 10,
      currentPageNo: "1",
      currentPageSize: 10
    }
  })
  // 创建 Blob 对象
  const blob = new Blob([info], { type: 'application/pdf' });

  // 创建下载链接
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = '订单出库单.pdf'; // 设置下载文件名
  document.body.appendChild(link);
  link.click(); // 触发下载
  document.body.removeChild(link); // 移除链接

  // 释放 Blob URL
  URL.revokeObjectURL(link.href);
}

/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
/**
   * 操作栏
   */
function getTableAction(record) {
  return [
    {
      label: '详情',
      onClick: handleDetail.bind(null, record),
    },
    {
      label: '出库单导出',
      onClick: handleExcelConfigId.bind(null, record),
      auth: 'lx:xl_customer_orde:pdfExport'
    },
    {
      label: '回传快递单号',
      ifShow: !record.deliveryCode,
      onClick: handleBackPassDelivery.bind(null, record),
      auth: 'lx:xl_customer_orde:backPass'
    },
    {
      label: '物流查询',
      ifShow: !!record.deliveryCode,
      onClick: handleQueryTrack.bind(null, record),
    },
    // {
    //   label: '收货凭证',
    //   ifShow: record.state === "1" && getProps('1'),
    //   onClick: handleSubmitTakeDelivery.bind(null, record),
    //   auth: 'lx:xl_customer_orde:submitTakeDelivery'
    // },
    // {
    //   label: '收货',
    //   ifShow: record.state === "2" && getProps('2'),
    //   onClick: handleTakeDelivery.bind(null, record),
    //   auth: 'lx:xl_customer_orde:takeDelivery'
    // },

  ]
}


/**
 * 下拉操作栏
 */
function getDropDownAction(record) {
  return [
  ]
}

</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>